#!/usr/bin/env python3
"""
便捷查看转录结果工具
用法: python3 view_result.py BV12bszzAEwq
"""

import sys
import requests
import json


def view_result(work_id, platform=0):
    """
    查看转录结果

    Args:
        work_id: 作品ID (如 BV12bszzAEwq)
        platform: 平台 (0=B站, 1=抖音, 2=小红书)
    """
    platform_names = {0: 'B站', 1: '抖音', 2: '小红书'}

    print("=" * 100)
    print(f"查询作品转录结果")
    print("=" * 100)
    print(f"作品ID: {work_id}")
    print(f"平台: {platform_names.get(platform, '未知')}")
    print("=" * 100)

    # 调用API查询
    url = 'http://localhost:8001/admin/work/transcribe_result/byPlatformWorkId'
    params = {
        'platform': platform,
        'workId': work_id
    }

    try:
        response = requests.get(url, params=params, timeout=5)

        if response.status_code == 200:
            result = response.json()

            if result.get('code') == 1000:
                data = result.get('data', {})
                work_info = data.get('workInfo', {})

                # 作品信息
                print(f"\n【作品信息】")
                print(f"标题: {work_info.get('title', 'N/A')}")
                print(f"作者: {work_info.get('author', 'N/A')}")
                print(f"关键词: {work_info.get('searchKeyword', 'N/A')}")
                print(f"时长: {work_info.get('duration', 'N/A')}")
                print(f"发布时间: {work_info.get('publishTime', 'N/A')}")

                # 转录信息
                print(f"\n【转录信息】")
                print(f"语言: {data.get('language', 'N/A')}")
                print(f"转录引擎: {data.get('engine', 'N/A')}")
                print(f"处理时间: {data.get('processingTime', 0):.2f}秒")
                print(f"片段数: {data.get('segmentCount', 0)}")

                # 原始转录文本
                raw_text = data.get('textContent', '')
                print(f"\n【原始转录文本】 ({len(raw_text)} 字符)")
                print("-" * 100)
                if raw_text == '[纯音乐]':
                    print("⚠ 此视频被识别为纯音乐，无人声内容")
                else:
                    print(raw_text)
                print("-" * 100)

                # 润色文本
                is_polished = data.get('isPolished', False)
                if is_polished:
                    polished_text = data.get('polishedText', '')
                    polish_status = data.get('polishStatus', 'N/A')
                    polish_engine = data.get('polishEngine', 'N/A')

                    print(f"\n【润色信息】")
                    print(f"润色状态: {polish_status}")
                    print(f"润色引擎: {polish_engine}")

                    print(f"\n【润色后文本】 ({len(polished_text)} 字符)")
                    print("-" * 100)
                    print(polished_text)
                    print("-" * 100)

                    # 对比
                    print(f"\n【效果对比】")
                    print(f"原始字符数: {len(raw_text)}")
                    print(f"润色字符数: {len(polished_text)}")
                    print(f"字符变化: {len(polished_text) - len(raw_text):+d}")
                else:
                    print(f"\n【润色状态】")
                    print("⚠ 该作品未进行润色")

            else:
                print(f"\n❌ 查询失败: {result.get('message', '未知错误')}")
        else:
            print(f"\n❌ HTTP错误: {response.status_code}")

    except requests.exceptions.ConnectionError:
        print("\n❌ 无法连接到后台服务，请确保后台服务已启动")
        print("启动命令: cd backend/cool_service && npm run dev")
    except Exception as e:
        print(f"\n❌ 查询出错: {str(e)}")

    print("\n" + "=" * 100)


def list_recent_results(limit=10):
    """查看最近的转录结果列表"""
    print("=" * 100)
    print(f"最近 {limit} 条转录结果")
    print("=" * 100)

    # 调用统计接口
    url = 'http://localhost:8001/admin/work/transcribe_result/stats'

    try:
        response = requests.get(url, timeout=5)

        if response.status_code == 200:
            result = response.json()

            if result.get('code') == 1000:
                data = result.get('data', {})

                print(f"\n【统计信息】")
                print(f"总转录数: {data.get('total', 0)}")
                print(f"已润色数: {data.get('polished', 0)}")
                print(f"未润色数: {data.get('unpolished', 0)}")

                engine_stats = data.get('engineStats', [])
                if engine_stats:
                    print(f"\n【引擎统计】")
                    for stat in engine_stats:
                        print(f"  {stat.get('engine', 'N/A')}: {stat.get('count', 0)} 条")

                language_stats = data.get('languageStats', [])
                if language_stats:
                    print(f"\n【语言统计】")
                    for stat in language_stats:
                        print(f"  {stat.get('language', 'N/A')}: {stat.get('count', 0)} 条")
            else:
                print(f"\n❌ 查询失败: {result.get('message', '未知错误')}")
        else:
            print(f"\n❌ HTTP错误: {response.status_code}")

    except requests.exceptions.ConnectionError:
        print("\n❌ 无法连接到后台服务，请确保后台服务已启动")
    except Exception as e:
        print(f"\n❌ 查询出错: {str(e)}")

    print("\n" + "=" * 100)
    print("\n提示: 使用 'python3 view_result.py <作品ID>' 查看具体作品的转录结果")
    print("例如: python3 view_result.py BV12bszzAEwq")
    print("=" * 100)


if __name__ == '__main__':
    if len(sys.argv) < 2:
        # 没有参数，显示统计信息
        list_recent_results()
    else:
        # 有参数，查看具体作品
        work_id = sys.argv[1]
        platform = int(sys.argv[2]) if len(sys.argv) > 2 else 0
        view_result(work_id, platform)
